package com.example.jwt.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.jwt.demo.annotation.PassToken;
import com.example.jwt.demo.annotation.UserLoginToken;
import com.example.jwt.demo.entity.ResponseResult;
import com.example.jwt.demo.entity.User;
import com.example.jwt.demo.service.impl.TokenServiceImpl;
import com.example.jwt.demo.service.impl.UserServiceImpl;
import com.example.jwt.demo.utils.TokenUtil;
import io.swagger.annotations.ApiOperation;
import org.mybatis.logging.Logger;
import org.mybatis.logging.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    TokenServiceImpl tokenService;

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    @ApiOperation(value = "用户查询服务",notes = "查询所有用户")
    @ResponseBody
    public Object login(User users, HttpServletResponse response){
        JSONObject jsonObject=new JSONObject();
        System.out.println(users);
        User usersForBase=new User();
        if(userService.findUserByUsername(users).size()>0){
            userService.findUserByUsername(users).forEach((item)->{
                usersForBase.setId(item.getId());
                usersForBase.setUsername(item.getUsername());
                usersForBase.setPassword(item.getPassword());
            });
        }
        if(!usersForBase.getPassword().equals(users.getPassword())){
            jsonObject.put("message","登录失败");
            return jsonObject;
        }else{
            String token=tokenService.getToken(usersForBase);
            jsonObject.put("token",token);

            Cookie cookie=new Cookie("token",token);
            cookie.setPath("/");
            response.addCookie(cookie);
            return jsonObject;
        }
    }

    //测试有token才能访问的接口
    @UserLoginToken
    @RequestMapping(value = "/getmessage",method = RequestMethod.GET)
    @ResponseBody
    public String getMessage(){
        return TokenUtil.getToken();
    }
    @PostMapping("/insertUser")
    public ResponseResult insert(@RequestBody User user){
        System.out.println("121");
        return userService.insertUser(user);
    }
}

